<?php

namespace App\Console\Commands;

use App\Http\Controllers\Api\MiniProgramController;
use App\Models\Flow;
use App\Models\Order;
use App\Models\ProductSku;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CancelOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cancel:order';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //删除那些过期未支付订单，回滚库存
        $orders = Order::where('status',NO_PAY)->OrderBy('id','asc')->limit(100)->get();
        //print_r($orders);
        if ($orders) {
            DB::beginTransaction();
            foreach ($orders as $order) {
                if (strtotime($order['created_at']) + config('order.max_time_to_pay') < time()) {
                    //调用微信支付查单接口，确认订单是否支付
                    $mp_controller = new MiniProgramController();
                    $order_query = $mp_controller->payment_query($order->no);
                    if ($order_query['status'] == true) {
                        $order->status = TO_DELIVERY;
                        $order->time_end = $order_query['time_end'];
                        $order->save();
                        continue;
                    }elseif ($order_query['status'] == 'USERPAYING') {//跳过支付中的订单
                        continue;
                    }else {
                        if ($order_query['err_code'] == 'SYSTEMERROR ') {//返回系统错误时，需要再次调用查单接口
                            sleep(3);
                            $order_query = $mp_controller->payment_query($order->no);
                            if ($order_query['status'] == true) {
                                $order->status = TO_DELIVERY;
                                $order->time_end = $order_query['time_end'];
                                $order->save();
                                continue;
                            }elseif ($order_query['status'] == 'USERPAYING') {
                                continue;
                            }
                        }
                    }
                    $order->delete();
                    $sku = ProductSku::withTrashed()->find($order['sku_id']);
                    if ($sku) {
                        $sku->increment('stock',$order['num']);
                    }
                    //删除流水记录
                    Flow::where('type',ORDER)->where('business_id',$order->id)->delete();
                }
            }
            DB::commit();
        }
    }
}
